﻿using System;
using System.IO;
using Skynet.CommonLibrary.Extension;
using IDataCenterContract;

namespace SQLQuery.Common
{
    class UpdateHelper
    {
        public static bool Update(Action beforAction)
        {
            try
            {
                System.Reflection.AssemblyName name = System.Reflection.AssemblyName.GetAssemblyName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                if (IsDown(name.Version.ToString(), Path.GetFileName(name.CodeBase)))
                {
                    if (File.Exists("Update.exe"))
                    {
                        if (beforAction != null)
                        {
                            beforAction();
                        }
                        ExecUpdate(name.CodeBase.Replace("file:///", ""));
                        return true;
                    }
                    MessageBoxHelper.Show("更新程序不存在，无法进行更新。");
                }
                else
                {
                    MessageBoxHelper.Show("已经是最新版本了");
                }
            }
            catch (Exception ex)
            {
                MessageBoxHelper.Show("无法连接到更新服务器，无法更新。\r详细:" + ex.Message);
            }
            return false;
        }

        private static void ExecUpdate(string path)
        {
             //更新程序复制到缓存文件夹
// ReSharper disable PossiblyMistakenUseOfParamsMethod
            string appDir = Path.Combine(System.Reflection.Assembly.GetEntryAssembly().Location.Substring(0, System.Reflection.Assembly.GetEntryAssembly().Location.LastIndexOf(Path.DirectorySeparatorChar)));
// ReSharper restore PossiblyMistakenUseOfParamsMethod

            string updateFileDir = Path.Combine(appDir, "UpdateCopy");

            if (!Directory.Exists(updateFileDir))
            {
                Directory.CreateDirectory(updateFileDir);
            }

            if (!Directory.Exists(updateFileDir))
            {
                Directory.CreateDirectory(updateFileDir);
            }
            string exePath = Path.Combine(updateFileDir, "Update.exe");

            File.Copy(Path.Combine(appDir, "Update.exe"), exePath, true);
            exePath.StartProcessEx(path, Directory.GetCurrentDirectory());
        }

        /// <summary>
        /// 查看是否有可下载的更新文件
        /// </summary>
        /// <param name="version">版本号</param>
        /// <param name="paraName">本程序名称</param>
        /// <returns></returns>
        public static bool IsDown(string version, string paraName)
        {
            IDownLoadFile down = DynamicInterfaceHelper.ConvertAnonymousTypeToInterface<IDownLoadFile>();
            return down.IsDown(version, paraName);
        }
    }
}
